import pickle


class AssessIndex:
    """
    评价指标 查准率P，查全率R，F度量
    """

    def __init__(self, test_data=[],
                 res_path='./docs/corpus/resultData/2014_fmm_result.txt'):
        self.test_data = test_data
        self.res_path = res_path

    def precision_and_recall(self):
        right_cnt = 0
        test_cnt = 0
        result_cnt = 0
        res_data_len = 0

        file = open(self.res_path, encoding='utf-8')
        result_data = file.readlines()

        for i, sentence in enumerate(result_data):
            res_elements = set(sentence.strip().split(' '))
            text_elements = set(self.test_data[i].strip().split(' '))
            # print(res_elements)
            # print(text_elements)
            inter_elements = res_elements.intersection(set(text_elements))

            # print(inter_elements)

            result_cnt += len(res_elements)
            right_cnt += len(inter_elements)
            res_data_len = i + 1

        for sentence in self.test_data[:res_data_len]:
            test_cnt += len(sentence.strip().split(' '))

        p = right_cnt / result_cnt
        r = right_cnt / test_cnt
        return round(p, 4), round(r, 4)

    def f_measure(self):
        p, r = self.precision_and_recall()
        f = 2 * p * r / (p + r)
        return round(f, 4)
